package com.ziq.base.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;

/**
 * 合规需要，不能使用获取运行中的进程
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class ProcessUtils {
    @Nullable
    public static String getCurrentProcessName(@NonNull Context context) {
        String name = getProcessNameByApplication(context);
        if (!TextUtils.isEmpty(name)) {
            return name;
        }
        name = resolveLinuxProcessName();
        return name;
    }

    @SuppressLint({"PrivateApi", "DiscouragedPrivateApi"})
    public static String getProcessNameByApplication(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return Application.getProcessName();
        } else {
            try {
                Class<?> clazz = Class.forName("android.app.ActivityThread",
                        true, Application.class.getClassLoader());
                Method method = clazz.getDeclaredMethod("currentProcessName");
                method.setAccessible(true);
                Object result = method.invoke(null);
                if (result instanceof CharSequence) {
                    return result.toString();
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @SuppressWarnings("all")
    public static String resolveLinuxProcessName() {
        FileInputStream in = null;
        try {
            String fn = "/proc/self/cmdline";
            in = new FileInputStream(fn);
            byte[] buffer = new byte[256];
            int len = 0;
            int b;
            while ((b = in.read()) > 0 && len < buffer.length) {
                buffer[len++] = (byte) b;
            }
            if (len > 0) {
                String s = new String(buffer, 0, len, Charset.forName("UTF-8"));
                return s;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
